using IMServer.Models.Message;
using IMServer.Services;

namespace IMServer.Endpoints
{
    public static class FriendEndpoint
    {
        public static RouteGroupBuilder MapFriendApi(this RouteGroupBuilder group)
        {
            group.MapPost("/add", async (HttpContext context) =>
            {
                try 
                {
                    var addFriendReq = await context.Request.ReadFromJsonAsync<AddFriendRequest>();
                    if (addFriendReq == null)
                    {
                        return Results.BadRequest(new 
                        { 
                            Code = "1004",
                            Message = "无效的请求体"
                        });
                    }
                    
                    addFriendReq.GenerateMessageId();

                    // 验证用户是否存在
                    var receiver = await UserDbService.Instance.GetUserByUserIdAsync(addFriendReq.ReceiverId);

                    // 设置系统消息的基本信息
                    addFriendReq.Content = $"{addFriendReq.SenderName} 请求添加您为好友";
                    
                    // 通过 WebSocket 发送消息
                    var success = await WebSocketManager.Instance.SendMessageToUserAsync(
                        addFriendReq.ReceiverId,
                        addFriendReq.ToJson()
                    );

                    // 插入到待处理消息箱
                    await PendingRequestBoxesDbService.Instance.InsertPendingRequestAsync(receiver.UserId,
                        addFriendReq);

                    return Results.Ok(new 
                    { 
                        Code = "0000",
                        Message = success ? "好友请求已发送" : "好友请求已保存，用户当前不在线"
                    });
                }
                catch (Exception ex)
                {
                    return Results.BadRequest(new 
                    { 
                        Code = "5000",
                        Message = $"服务器通用错误: {ex.Message}"
                    });
                }
            });

            group.MapPost("/response", async (HttpContext context) =>
            {
                try 
                {
                    var response = await context.Request.ReadFromJsonAsync<AddFriendResponse>();

                    if (response == null)
                    {
                        return Results.BadRequest(new 
                        { 
                            Code = "1004",
                            Message = "无效的请求体"
                        });
                    }
                    
                    response.GenerateMessageId();

                    // TODO:验证原请求者是否存在
                    var requester = await UserDbService.Instance.GetUserByUserIdAsync(response.ReceiverId);
                    
                    // 如果接受请求，则建立好友关系
                    if (response.Accepted)
                    {
                        // 双向添加好友
                        await UserDbService.Instance.AddFriendAsync(response.SenderId, response.ReceiverId);
                        await UserDbService.Instance.AddFriendAsync(response.ReceiverId, response.SenderId);
                    }
                    
                    // 通过 WebSocket 发送消息
                    var success = await WebSocketManager.Instance.SendMessageToUserAsync(
                        response.ReceiverId,
                        response.ToJson()
                    );
                    
                    await PendingRequestBoxesDbService.Instance.InsertPendingRequestAsync(response.SenderId,
                        response);

                    return Results.Ok(new 
                    { 
                        Code = "0000",
                        Message = success ? 
                            (response.Accepted ? "已接受好友请求" : "已拒绝好友请求") : 
                            "响应已保存，用户当前不在线"
                    });
                }
                catch (Exception ex)
                {
                    return Results.BadRequest(new 
                    { 
                        Code = "5000",
                        Message = $"服务器通用错误: {ex.Message}"
                    });
                }
            });

            return group;
        }
    }
}